var express = require("express");
var router = express.Router();
var { TieModel, GoldModel, BiaoModel, UserModel, ChatModel, HomegoodModel, OrderModel, RecommentModel, TopicModel } = require("../model/model");
var jwt = require('jsonwebtoken')
var multiparty = require("multiparty")
const ws = require('nodejs-websocket')
/* GET home page. */
// WebSocket功能
let count = 0
var server = ws.createServer(connect => {
  console.log('有用户连接了！');
  count++
  broadcast({
    type: 'ENTER',
    msg: `${count}进来了！`,
    time: new Date().toLocaleTimeString()
  })

  connect.on('text', (data) => {

    broadcast({
      type: 'MESSAGE',
      msg: data,
      time: new Date().toLocaleTimeString()
    })

  })

  connect.on('close', (data) => {
    console.log('连接断开');
    broadcast({
      type: 'LEAVE',
      msg: `${connect.user}离开了聊天室`,
      time: new Date().toLocaleTimeString()
    })
    count--
  })
  connect.on('error', (data) => {
    console.log('连接异常', data);
  })
})
function broadcast(data) {
  server.connections.forEach(item => {
    item.send(JSON.stringify(data))
  })
}
server.listen(4000, () => {
  console.log('WebSocket启动');
})
router.get('/ceshi', (req, res) => {
  res.send({
    code: 200,
    msg: '测试成功'
  })
})

// 日常接口
router.post('/Login', async (req, res) => {
  let { username, password } = req.body
  let data = await UserModel.find({ user: username })
  if (data[0]) {
    if (data[0].password === password) {
      let token = 'Berry' + jwt.sign({ username }, 'token', { expiresIn: '72h' })
      res.send({
        code: 201,
        token: token,
        id: data[0]._id,
        msg: '登录成功！'
      })
    } else {
      res.send({
        code: 202,
        msg: '密码错误！'
      })
    }
  } else {
    res.send({
      code: 203,
      msg: '用户不存在！'
    })
  }

})
router.post("/register", (req, res) => {
  const { user, password, name, guanzhu, fensi, beizan, score, uni } = req.body;

  UserModel.create({
    user: user,
    password: password,
    img: 'head.jpg',
    name: name || user,
    guanzhu: guanzhu || 0,
    fensi: fensi || 0,
    beizan: beizan || 0,
    score: score || 0,
    uni: uni || 0,
    guanzhuId: req.body.guanzhuId || []
  })
  res.send({
    code: 200,
    msg: "注册成功"
  })
})

router.get("/getList", async (req, res) => {
  let data = await BiaoModel.find();
  res.send({
    code: 200,
    data: data,
    msg: "获取成功",
  });
});
router.post('/getMy', async (req, res) => {
  let data = await UserModel.find({ _id: req.body.id })
  res.send({
    code: 200,
    data: data[0],
    msg: '获取个人信息成功'
  })
})
router.get("/getUser", async (req, res) => {
  let data = await UserModel.find();
  let ChatData = await ChatModel.find()
  res.send({
    code: 200,
    data: data,
    data1: ChatData,
    msg: '获取成功'
  });
});
router.get("/getOrder", async (req, res) => {
  let data = await OrderModel.find();
  res.send({ code: 200, data });
});
router.get("/getComment", async (req, res) => {
  let data = await RecommentModel.find()
  res.send({ code: 200, data })
})
router.get("/getTopic", async (req, res) => {
  let data = await TopicModel.find()
  res.send({ code: 200, data })
})
router.post("/addOrder", async (req, res) => {
  await OrderModel.create(req.body);
  res.send({ code: 200 });
});
router.post("/add", async (req, res) => {
  await UserModel.create(req.body);
  res.send({ code: 200 });
});
router.post('/delComment', async (req, res) => {
  await RecommentModel.deleteOne({ _id: req.body.id })
  let data = await RecommentModel.find()
  res.send({
    code: 200,
    data: data,
    msg: '删除成功！'
  })
})
// 发送消息
router.post('/sendChat', async (req, res) => {
  let newData = req.body
  newData.time = new Date()
  await ChatModel.create(newData)
  let data = await ChatModel.find().populate('sendId').populate('acceptId')
  res.send({
    code: 200,
    data: data,
    msg: '发送成功'
  })
})
// 获取所有消息
router.get('/getChat', async (req, res) => {
  let data = await ChatModel.find().populate('sendId').populate('acceptId')
  res.send({
    code: 200,
    data: data,
    msg: '获取成功'
  })
})
function fuzzyQuery(list, keyWord) {
  let queryStringArr = keyWord.split('')
  var arr = []
  for (var j = 0; j < queryStringArr.length; j++) {
    for (var i = 0; i < list.length; i++) {
      if (list[i].title.match(queryStringArr[j]) !== null) {
        let idx = arr.findIndex(item => item._id == list[i]._id)
        if (idx == -1) {
          arr.push(list[i])
        }
      }
    }
  }
  return arr
}
router.post('/gethomegood', async (req, res) => {
  let body = req.body
  let str = body.str
  let type = body.type

  let homegood = await HomegoodModel.find()

  if (str !== '') {
    if (type === 'search') {
      homegood = fuzzyQuery(homegood, str)
    } else if (type === '') {
      homegood = homegood.filter(item => item.type === str)
    }
  }
  res.send({
    code: 200,
    homegood
  })
})

router.get('/search', async (req, res) => {
  let { key } = req.query
  let data = await HomegoodModel.find({ title: { $regex: key } });
  res.send({
    code: 200,
    data
  })
})

router.post("/add_img", (req, res) => {
  let form = new multiparty.Form()
  form.uploadDir = "upload"
  form.parse(req, (err, fdata, idata) => {
    res.send({
      code: 200,
      msg: "上传完成",
      path: "http://localhost:3000/" + idata.file[0].path
    })
  })
})

router.get("/glod_get", async (req, res) => {
  let { title, _id, name } = req.query
  let data = []
  if (title) {
    data = await GoldModel.find({ title })
  } else if (_id) {
    data = await TieModel.find({ Fid: _id })
  } else if (name) {
    data = await GoldModel.find({ _id: name })
  } else {
    data = await GoldModel.find()
  }
  res.send({
    code: 200,
    data
  })
})

router.post("/d_add", async (req, res) => {
  await TieModel.create(req.body)
  res.send({
    code: 200,
    msg: "新增完成"
  })
})

router.put("/g_put", async (req, res) => {
  let { _id } = req.query
  await GoldModel.updateOne({ _id }, req.body)
  res.send({
    code: 200
  })
})


module.exports = router;
